import os
import subprocess
from src.mod import run
from src.core import log
from src.mod import Resource
from datetime import datetime
from src.mod import safe_remove
from src.core.variables.info import sof
from src.core.variables.constant import CONF


class Unzip:
    def __init__(self, ):
        self.version = ""
        self.os_install = False
        self.install = False
        self.pkg = Resource()
        self.pkg_path = self.pkg.unzip.path
        self.__check_install()
        if self.os_install:
            ...
        if not self.install:
            self.__compile()
            self.__clear_temp()
    
    def __compile(self, configure_param={}):
        log.INFO(f"渔翁自编译：fm_unzip_6.10b(基于unzip_6.10b)开始编译...")
        now = datetime.now()
        log_path = open(f'{CONF.PATH.ABS}/logs/{now}_unzip.log', 'a+')
        if not os.path.exists(self.pkg_path):
            raise FileNotFoundError(f"压缩包不存在: {self.pkg_path}")
        target_dir = f"{CONF.PATH.ABS}/data/temp/fm_unzip"
        os.makedirs(target_dir, exist_ok=True, mode=0o755)
        run(f"tar -zxvf {self.pkg_path} -C {target_dir}")
        contents = os.listdir(target_dir)
        if not contents:
            raise RuntimeError(f"解压后的目录为空: {target_dir}")
        source_dir = os.path.join(target_dir, contents[0])
        configure_str = " ".join(
            f"{k}={v}" for k, v in self.pkg.unzip.default_configure_param.items()
        ) + " ".join(f"{k}={v}" for k, v in configure_param.items())
        # 编译命令
        cmd = f"""
        cd {source_dir}
        make -f unix/Makefile generic
        make -f unix/Makefile {configure_str} install
        """
        # 执行编译
        process = subprocess.Popen(
            cmd, shell=True, stdout=log_path, stderr=subprocess.STDOUT, text=True
        )
        stdout, stderr = process.communicate()
        if process.returncode != 0:
            raise RuntimeError(f"编译失败：{stderr}")
        log.INFO(f"渔翁自编译：fm_unzip_6.10b(基于unzip_6.10b)编译成功！")
    
    def __check_install(self, ):
        """检查是否安装"""
        if run('which unzip'):
            self.install = True
            self.version = "--"
            self.os_install = True
            log.INFO(f"中间件 渔翁发现系统已安装的 'unzip'")
            sof.os_unzip = True
            return
        result = ""
        if os.path.exists(self.pkg.unzip.install_path):
            try:
                result = run(f"{self.pkg.unzip.install_path}/bin/unzip -v")
                if "UnZip 6.10b BETA of 10 Dec 10" in result:
                    self.install = True
                    self.version = "6.10b"
                    log.INFO(f"中间件 渔翁发现自编译的 'fm_unzip'")
                    sof.fm_unzip = True
                    return
            except Exception as e:
                log.ERROR(f"获取fm_unzip版本失败: {e}")
        log.INFO(f"未检测到渔翁自编译的fm_unzip！")
    
    def __clear_temp(self, ):
        """清理缓存"""
        safe_remove(f"{CONF.PATH.ABS}/data/temp/fm_unzip", is_dir=True)
        log.DEBUG(f'删除编译缓存。')

    def __call__(self, zip_path, target_path):
        if not os.path.exists(target_path):
            os.makedirs(target_path, exist_ok=True, mode=0o755)
        program_path = f'{CONF.PATH.ABS}/data/software/fm_unzip/bin/unzip' if not self.os_install else 'unzip'
        result = run(f'{program_path} {zip_path} -d {target_path}')
        return result